package com.ThreadPool;

import java.util.concurrent.*;

//线程池2
// 用new ThreadPoolExecutor 创建线程池
public class Pool2 {
    public static void main(String[] args) {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                20, 20,
                3, TimeUnit.SECONDS,new LinkedBlockingQueue<Runnable>(30),
                Executors.defaultThreadFactory(),new ThreadPoolExecutor.AbortPolicy());

        System.out.println(Runtime.getRuntime().availableProcessors());

        //最大承载数 指总的线程数(设定最大线程数+设定队列大小) 超出就会异常
        //此时是 核心 5  最大10 队列10  25
        Semaphore semaphore = new Semaphore(5);
        try {
            for (int i = 0; i < 45; i++) {
                threadPoolExecutor.execute(()->{
                    try {
                        //结合 并发辅助
                        semaphore.acquire();
                        System.out.println(Thread.currentThread().getName()+" 抢到车位");
//                        TimeUnit.SECONDS.sleep(1);
                        System.out.println(Thread.currentThread().getName()+" 离开..");
//                        System.out.println(Thread.currentThread().getName()+" - 启动执行");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }finally {
                        semaphore.release();
                    }

                });
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            threadPoolExecutor.shutdown();
        }


    }
}
